package com.das.mechanic_base.mvp.view.alone;

import android.app.Activity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.alone.X3NewAloneServiceItemAdapter;
import com.das.mechanic_base.adapter.alone.X3NewAloneTitleAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseFragment;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.BtnCommitBean;
import com.das.mechanic_base.bean.alone.NewServiceHeaderBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.utils.X3AloneServiceSearchUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.widget.X3BottomAffirmMileDialog;
import com.das.mechanic_base.widget.X3NewBottomMileOrTimeDialog;
import com.das.mechanic_base.widget.X3PointDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class X3NewWebAloneServiceFragment extends X3BaseFragment implements X3NewAloneTitleAdapter.IOnShowTilte, X3NewAloneServiceItemAdapter.IOnClickService, X3NewBottomMileOrTimeDialog.IOnAffirmSelect {
    RecyclerView rlv_second;
    RecyclerView rlv_service;
    private boolean isEdit = false;//是否删除或者添加
    private X3NewAloneTitleAdapter titleAdapter;
    private HashMap<String, Integer> titleMap;
    private List<NewServiceHeaderBean.AllSerViceListBean.ListBeanX> mList;
    private X3NewAloneServiceItemAdapter itemAdapter;
    private int questionBaseId;
    private String decTitle;
    private int lastVisibleIndex = 0;
    private NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> cacheList;
    private List<NewServiceHeaderBean.AlreadyInPlanListBean> newCacheList;
    private boolean needUpdateMile;
    private NewServiceHeaderBean.AlreadyInPlanListBean changeServiceBean;
    private X3BottomAffirmMileDialog mileDialog;
    private int workBaseId;
    private double newPerMiles;
    private double newCurrentMile;
    private Map<String, AloneServiceListBean> aloneMap;

    public X3NewWebAloneServiceFragment(List<NewServiceHeaderBean.AllSerViceListBean.ListBeanX> mList, int questionBaseId, String decTitle, List<NewServiceHeaderBean.AlreadyInPlanListBean> cacheList) {
        this.mList = mList;
        this.questionBaseId = questionBaseId;
        this.decTitle = decTitle;
        this.cacheList = cacheList;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_fragment_new_web_alone_service;
    }

    @Override
    protected void initView(View view) {
        needUpdateMile = getActivity().getIntent().getBooleanExtra("needUpdateMile", false);
        workBaseId = getActivity().getIntent().getIntExtra("workBaseId", 0);
        rlv_second = view.findViewById(R.id.rlv_second);
        rlv_service = view.findViewById(R.id.rlv_service);
        rlv_second.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false));
        rlv_service.setLayoutManager(new LinearLayoutManager(getActivity()));
        titleAdapter = new X3NewAloneTitleAdapter(getActivity());
        rlv_second.setAdapter(titleAdapter);
        titleAdapter.setiOnShowTilte(this);
        titleAdapter.changeTitleList(mList);
        itemAdapter = new X3NewAloneServiceItemAdapter(getActivity());
        rlv_service.setAdapter(itemAdapter);
        itemAdapter.setiOnClickService(this);

        List<NewServiceHeaderBean.AlreadyInPlanListBean> baseList = new ArrayList<>();
        titleMap = new HashMap<>();
        if (!X3StringUtils.isListEmpty(mList)) {
            for (int i = 0; i < mList.size(); i++) {
                if (!titleMap.containsKey(mList.get(i).shopCategoryName)) {
                    titleMap.put(mList.get(i).shopCategoryName,baseList.size());
                }
                List<NewServiceHeaderBean.AlreadyInPlanListBean> serviceBaseEntityList = mList.get(i).list;
                if (X3StringUtils.isListEmpty(serviceBaseEntityList)) {
                    break;
                }
                baseList.addAll(serviceBaseEntityList);
            }
        }

        if (itemAdapter != null) {
            itemAdapter.changeServiceItem(baseList);
        }

        rlv_service.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (((Activity)getActivity()).isFinishing()) {
                    return;
                }
                if(rlv_service == null){
                    return;
                }

                if(rlv_service.getLayoutManager() == null){
                    return;
                }

                int visiblePosition = ((LinearLayoutManager) rlv_service.getLayoutManager()).findFirstVisibleItemPosition();
                if (titleMap == null) {
                    return;
                }
                int visibleIndex = -1;
                for (String key : titleMap.keySet()) {
                    if (visiblePosition >= titleMap.get(key)) {
                        visibleIndex++;
                    }
                }
                if (visibleIndex == -1) {
                    return;
                }
                if (lastVisibleIndex == visibleIndex) {
                    return;
                }
                if (titleAdapter != null) {
                    titleAdapter.changeTitleSelectList(visibleIndex);
                    lastVisibleIndex = visibleIndex;
                }
            }
        });

    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void iOnShowTitleItem(String title) {
        if (titleMap == null) {
            return;
        }
        int index = titleMap.get(title);
        ((LinearLayoutManager)rlv_service.getLayoutManager()).scrollToPositionWithOffset(index,0);
        ((LinearLayoutManager)rlv_service.getLayoutManager()).setStackFromEnd(true);
    }

    @Override
    public void iOnCuteService(boolean isCute, NewServiceHeaderBean.AlreadyInPlanListBean serviceBean, int position) {
        serviceListBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList,serviceBean.serviceBaseSn);

        if (isCute) {
            /**
             * 将这个服务项目从缓存中去除
             */
            if (serviceListBean == null) {
//                searchAloneCache();
                return;
            }
            cacheList = X3AloneServiceSearchUtils.replaceNewAloneServiceBean(cacheList,serviceListBean.serviceBaseSn,serviceListBean);
            Iterator<NewServiceHeaderBean.AlreadyInPlanListBean> iterator = cacheList.iterator();
            while (iterator.hasNext()) {
                NewServiceHeaderBean.AlreadyInPlanListBean next = iterator.next();
                if (next.serviceBaseSn.equals(serviceListBean.serviceBaseSn)) {
                    iterator.remove();
                }
            }
            newCacheList = cacheList;
            isEdit = true;
//            changeButtonStustas();
            BtnCommitBean btnCommitBean = new BtnCommitBean();
            btnCommitBean.cacheList = newCacheList;
            btnCommitBean.isEdit = isEdit;
            btnCommitBean.type = "BTNCOMMIT";
            EventBus.getDefault().post(btnCommitBean);

        }else {
            if (!needUpdateMile) {
                serviceListBean = addServiceItem(serviceBean, serviceListBean);
                iOnShowChangeServiceOne(serviceListBean, serviceListBean.reductionType);
            }else {
                // 否则需要先确认总里程和日均里程
                mileDialog = new X3BottomAffirmMileDialog(getActivity());
                mileDialog.show();
                mileDialog.setWorkBaseId(workBaseId,null);
                mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                    // 确认完总里程和日均里程了
                    needUpdateMile = false;

                    newPerMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                    newCurrentMile = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));

                    CameraBean cameraBean = new CameraBean();
                    cameraBean.currentMiles = newCurrentMile;
                    cameraBean.perMiles = newPerMiles;
                    EventBus.getDefault().post(new CameraBean(X3Constent.CODE_ALONE_CHANGE_NEED_UPDATE,cameraBean));

                    serviceBean.currentMiles = newCurrentMile;
                    serviceBean.perMiles = newPerMiles;

                    serviceListBean = addServiceItem(serviceBean, serviceListBean);

//                    if (mPresenter != null) {
//                        mPresenter.getDetectionServiceList();
//                    }
                    if (itemAdapter != null) {
                        itemAdapter.refreshMiles(newCurrentMile, newPerMiles);
                    }

                    iOnShowChangeServiceOne(serviceListBean,serviceListBean.reductionType);
                });
            }
        }

    }

    @Override
    public void iOnShowChangeService(String sn, String remindType, double currentMiles, double perMiles) {
        changeServiceBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList,sn);
        changeServiceBean.currentMiles = currentMiles;
        changeServiceBean.perMiles = perMiles;
        modifyMileOrTime(changeServiceBean,remindType);
    }

    @Override
    public void iOnShowDelete(int position, String sn) {
        NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean = X3AloneServiceSearchUtils.searchNewAloneServiceBean(cacheList,sn);
        if (serviceListBean == null) {
            return;
        }
        String s = X3FileUtils.loadDataFromFile(getActivity(), workBaseId + serviceListBean.serviceBaseSn);
        aloneMap = null;
        if (!X3StringUtils.isEmpty(s)) {
            aloneMap = new Gson().fromJson(s,new TypeToken<Map<String, AloneServiceListBean>>(){}.getType());
        }

        X3PointDialog delDialog = new X3PointDialog(getActivity(),"",getString(R.string.x3_delete_add_service),getString(R.string.x3_cancel_info),getString(R.string.x3_affirm_info));
        delDialog.show();
        delDialog.setRightClick(view -> {
            delDialog.dismiss();
            if (itemAdapter != null) {
                itemAdapter.deleteService(position,true,true);
            }
        });
    }

    private NewServiceHeaderBean.AlreadyInPlanListBean addServiceItem(NewServiceHeaderBean.AlreadyInPlanListBean serviceBean,NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean1) {
        NewServiceHeaderBean.AlreadyInPlanListBean newServiceBean = serviceListBean1;
        if (newServiceBean == null) {
            newServiceBean = new NewServiceHeaderBean.AlreadyInPlanListBean();
            newServiceBean.nextReplaceCycleKm = serviceBean.nextReplaceCycleKm;
            newServiceBean.serviceBaseName = serviceBean.serviceBaseName;
            newServiceBean.serviceBaseSn = serviceBean.serviceBaseSn;
            newServiceBean.currentMiles = serviceBean.currentMiles;
            newServiceBean.perMiles = serviceBean.perMiles;
            newServiceBean.seleced = serviceBean.seleced;
            newServiceBean.carId = serviceBean.carId;
            newServiceBean.reductionType = serviceBean.reductionType;
            newServiceBean.warningDate = serviceBean.warningDate;

            cacheList.add(newServiceBean);
        }else {
            cacheList = X3AloneServiceSearchUtils.replaceNewAloneServiceBean(cacheList,newServiceBean.serviceBaseSn,newServiceBean);
        }
        return newServiceBean;
    }

    public void iOnShowChangeServiceOne(NewServiceHeaderBean.AlreadyInPlanListBean changeServiceBean,String remindType) {
        this.changeServiceBean = changeServiceBean;
        modifyMileOrTime(changeServiceBean,remindType);
    }

    private void modifyMileOrTime(NewServiceHeaderBean.AlreadyInPlanListBean changeServiceBean,String remindType) {
        if (changeServiceBean.currentMiles <= 0 && changeServiceBean.currentMiles <= 1) {
            changeServiceBean.perMiles = newPerMiles;
            changeServiceBean.currentMiles = newCurrentMile;
        }
        AloneServiceListBean aloneServiceListBean = new AloneServiceListBean();
        aloneServiceListBean.setPerMiles(changeServiceBean.perMiles);
        aloneServiceListBean.setCurrentMiles(changeServiceBean.currentMiles);
        aloneServiceListBean.setRecommendSafeMiles(changeServiceBean.nextReplaceCycleKm);
        aloneServiceListBean.setTouchServiceSn(changeServiceBean.serviceBaseSn);
        aloneServiceListBean.setWarningDate(changeServiceBean.warningDate);
        aloneServiceListBean.setReductionType(changeServiceBean.reductionType);
        aloneServiceListBean.setCarId(changeServiceBean.carId);
        aloneServiceListBean.setSeleced(true);
        aloneServiceListBean.setTouchServiceBaseName(changeServiceBean.serviceBaseName);

        X3NewBottomMileOrTimeDialog mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(getActivity(),2);
        mileOrTimeDialog.show();
        mileOrTimeDialog.showCurrentMile(aloneServiceListBean,remindType);
        mileOrTimeDialog.setiOnAffirmSelect(this);
    }


    @Override
    public void iOnAffirmMiles(AloneServiceListBean listBean) {
        isEdit = true;
        NewServiceHeaderBean.AlreadyInPlanListBean alreadyInPlanListBean = new NewServiceHeaderBean.AlreadyInPlanListBean();
        alreadyInPlanListBean.serviceBaseSn =listBean.getTouchServiceSn();
        alreadyInPlanListBean.currentMiles = listBean.getCurrentMiles();
        alreadyInPlanListBean.perMiles = listBean.getPerMiles();
        alreadyInPlanListBean.carId = listBean.getCarId();
        alreadyInPlanListBean.warningDate = listBean.getWarningDate();
        alreadyInPlanListBean.nextReplaceCycleKm = listBean.getRecommendSafeMiles();
        alreadyInPlanListBean.reductionType = listBean.getReductionType();
        alreadyInPlanListBean.seleced = listBean.isSeleced();

        boolean isHave = false;
        newCacheList = cacheList;
        for (int i = 0; i < newCacheList.size(); i++) {
            NewServiceHeaderBean.AlreadyInPlanListBean aloneServiceListBean = newCacheList.get(i);
            if (aloneServiceListBean.serviceBaseSn.equals(listBean.getTouchServiceSn())) {
                isHave = true;
                newCacheList.remove(i);
                newCacheList.add(i,alreadyInPlanListBean);
                break;
            }
        }
        if (!isHave) {
            newCacheList.add(alreadyInPlanListBean);
        }

//        changeButtonStustas();
        if (itemAdapter != null) {
            itemAdapter.changeMilesService(alreadyInPlanListBean);
        }
        BtnCommitBean btnCommitBean = new BtnCommitBean();
        btnCommitBean.cacheList = newCacheList;
        btnCommitBean.isEdit = isEdit;
        btnCommitBean.type = "BTNCOMMIT";
        EventBus.getDefault().post(btnCommitBean);


    }

    @Override
    public void iOnPickerDismiss() {
        CameraBean cameraBean = new CameraBean(X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST,cacheList);
        EventBus.getDefault().post(cameraBean);
    }
}
